//
//  PayOffViewController.m
//  HTP
//
//  Created by 王鑫 on 15/11/2.
//  Copyright © 2015年 nit. All rights reserved.
//

#import "PaidViewController.h"
#import "PayTableViewCell.h"
#import "PaidOrderInfoViewController.h"
#import "MyOrderViewModel.h"
#import "MyOrderModel.h"
#import "PayOffOrderInfoViewController.h"

#define LENGTH 5
#define LENGTHSTR @"5"
@interface PaidViewController () <BaseTableDelgate,UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, retain) BaseTableView *payTableView;

@property (nonatomic, retain) NSDictionary *order1stDic;

@property (nonatomic, retain) NSDictionary *order2rdDic;

@property (nonatomic, retain) NSMutableArray *orderArray;

@property (nonatomic, retain) NSMutableArray *orderMutableArray;

@property (nonatomic, retain) NSMutableArray *localArray;

@property (nonatomic, retain) NSMutableArray *interfaceArray;

@property (nonatomic, retain) MyOrderModel *cellData;

@property (nonatomic,assign) NSInteger  refreshFlag;//2是往后添加数据 1更新数据

@end

@implementation PaidViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _orderArray = [NSMutableArray array];
    [self.view addSubview:self.payTableView];
    [self getLocalOrderFirst];
    [self getFirstOrderList];
    // Do any additional setup after loading the view.
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

- (BaseTableView *)payTableView {
    if (!_payTableView) {
        _payTableView = [[BaseTableView alloc] initWithFrame:CGRectMake(0, 39, ScreenWidth, ScreenHeihgt - NavHe - 39) style:UITableViewStylePlain withHeadRefresh:YES andFoodRefresh:YES];
        _payTableView.backgroundColor = [UIColor colorWithRed:0.93 green:0.93 blue:0.93 alpha:0.7];
        _payTableView.delegate = self;
        _payTableView.dataSource = self;
        _payTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _payTableView.baseTableDelegate = self;
        _payTableView.tableHeaderView = nil;
        
    }
    
    return _payTableView;
}


//TODO:UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [_orderArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *Identifier = @"Identifier";
    PayTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Identifier];
    
    if (cell == nil) {
        cell = [[PayTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Identifier];
    }
    _cellData = [_orderArray objectAtIndex:indexPath.section];
    [cell setCellData:_cellData];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    PaidOrderInfoViewController *PaidOrderInfoView = [[PaidOrderInfoViewController alloc] init];
    _cellData = [_orderArray objectAtIndex:indexPath.section];
    PaidOrderInfoView.orderId = [NSString stringWithFormat:@"%@",_cellData.ordId];
    [[NSNotificationCenter defaultCenter] postNotificationName:ROOTGOTONEXTCONTROLLER object:PaidOrderInfoView];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 180;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
//    if (section < _orderArray.count-1) {
//        return 10;
//    }
    return 0;
}
//TODO: baseTable Delegate
-(void)headRefresh:tableView{
    if (_orderArray == nil || _orderArray.count == 0) {
        _refreshFlag = 1;
        [self getFirstOrderList];
    }else{
        MyOrderModel *orderM = (MyOrderModel *)[_orderArray lastObject];
        [self getLocalPullDwon:[NSNumber numberWithInt:[orderM.ordId intValue]] andParentId:[NSNumber numberWithInt:[[USERCONTENT getUserParentId] intValue]]];
        [self getPullDwonOrderList:[USERCONTENT getUserParentId] andOrderId:[NSString stringWithFormat:@"%d",([orderM.ordId intValue] -1)]];
    }
}
-(void)footRefresh:tableView{
    if (_orderArray == nil || _orderArray.count == 0) {
        _refreshFlag = 1;
        [self getFirstOrderList];
    }else{
        _refreshFlag = 2;
        MyOrderModel *orderM = (MyOrderModel *)[_orderArray lastObject];
        [self getLcoalOrderLength:LENGTH withLastOrderId:orderM.ordId];
        [self getFinishOrderList:[NSString stringWithFormat:@"%d",[orderM.ordId intValue]] andLength:LENGTHSTR];
    }
}
//TODO:获取数据
/**
 *  获取本地数据
 */
-(void)getLocalOrderFirst{
    NSPredicate *orderFilter = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"parentId = %@ AND ordStatus IN {2,3} ",[NSNumber numberWithInt:[[USERCONTENT getUserParentId] intValue]]]];
     NSArray *orderDatas = [OrderData findByPredicate:orderFilter andLimit:LENGTH andStart:0 BySorted:@"ordId" ascending:NO];
//    _localArray = [[NSMutableArray alloc] initWithArray:[MyOrderModel creatMyOrders:orderDatas]];
    _orderArray = [[NSMutableArray alloc] initWithArray:[MyOrderModel creatMyOrders:orderDatas]];
    [self.payTableView reloadData];
}
-(void)getLcoalOrderLength:(NSInteger)length withLastOrderId:(NSNumber *)orderId{
    NSPredicate *orderFilter = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"ordId < %@ AND parentId = %@ AND ordStatus IN {2,3}",orderId,[NSNumber numberWithInt:[[USERCONTENT getUserParentId] intValue]]]];
    NSArray *orderDatas = [OrderData findByPredicate:orderFilter andLimit:length andStart:0 BySorted:@"ordId" ascending:NO];
    [_orderArray addObjectsFromArray:[MyOrderModel creatMyOrders:orderDatas]];
    [self.payTableView reloadData];
}
-(void)getLocalPullDwon:(NSNumber *)orderId andParentId:(NSNumber *)parentId{
    NSPredicate *orderFilter = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"ordId >= %@ AND parentId = %@ AND ordStatus IN {2,3}",[NSNumber numberWithInt:[orderId intValue]],[NSNumber numberWithInt:[[USERCONTENT getUserParentId] intValue]]]];
    NSArray *orderDatas = [OrderData findByPredicate:orderFilter andLimit:10000 andStart:0 BySorted:@"ordId" ascending:NO];
    _orderArray = [NSMutableArray arrayWithArray:[MyOrderModel creatMyOrders:orderDatas]];
//    _orderArray = [NSMutableArray arrayWithArray:_localArray];
    [self.payTableView reloadData];
    
   
}
/**
 *  第一次获取网络数据
 *
 *  @param startOrderId
 *  @param length
 */
-(void)getFirstOrderList{
    MyOrderViewModel *myOrderViewModel = [[MyOrderViewModel alloc] init];
    [myOrderViewModel setBlockWithReturnBlock:^(id returnValue) {
        [self hiddenMbProgress];
        NSArray *dataArray = [MyOrderModel mj_objectArrayWithKeyValuesArray:returnValue[INTERFACE_INFO]];
        [dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            MyOrderModel *myOrder = (MyOrderModel *)obj;
            [myOrder saveBean];
        }];
        [self getLocalOrderFirst];
    } WithErrorBlock:^(id errorCode) {
        [self hiddenMbProgress];
    } WithFailureBlock:^{
        [self hiddenMbProgress];
    }];
    if (_orderArray.count != 0 || _orderArray != nil) {
        [self showMbProgress:@""];
    }
    [myOrderViewModel getFinishOrderList:@"0" length:LENGTHSTR andParentId:[USERCONTENT getUserParentId]];

}
/**
 *  上拉获取网络数据
 *
 *  @param startOrderId 根据id分割数据界线
 *  @param length
 */
-(void)getFinishOrderList:(NSString *)startOrderId andLength:(NSString *)length{
    MyOrderViewModel *myOrderViewModel = [[MyOrderViewModel alloc] init];
    [myOrderViewModel setBlockWithReturnBlock:^(id returnValue) {
        [self hiddenMbProgress];
        __block NSNumber *lastId = [NSNumber numberWithInt:0];
        NSArray *dataArray = [MyOrderModel mj_objectArrayWithKeyValuesArray:returnValue[INTERFACE_INFO]];
        [dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            MyOrderModel *myOrder = (MyOrderModel *)obj;
            lastId = myOrder.ordId;
            [myOrder saveBean];
        }];
        if (![lastId integerValue] > 0) {
            return ;
        }
        [self getPullDwonOrderList:[USERCONTENT getUserParentId] andOrderId:[NSString stringWithFormat:@"%@",lastId]];
    } WithErrorBlock:^(id errorCode) {
        [self hiddenMbProgress];
    } WithFailureBlock:^{
        [self hiddenMbProgress];
    }];
    if (_orderArray.count != 0 || _orderArray != nil) {
         [self showMbProgress:@""];
    }
   
    [myOrderViewModel getFinishOrderList:startOrderId length:length andParentId:[USERCONTENT getUserParentId]];
}
-(void)getPullDwonOrderList:(NSString *)parentId andOrderId:(NSString *)orderId{
    MyOrderViewModel *myOrderViewModel = [[MyOrderViewModel alloc] init];
    [myOrderViewModel setBlockWithReturnBlock:^(id returnValue) {
        [self hiddenMbProgress];
        NSArray *dataArray = [MyOrderModel mj_objectArrayWithKeyValuesArray:returnValue[INTERFACE_INFO]];
        [dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            MyOrderModel *myOrder = (MyOrderModel *)obj;
            [myOrder saveBean];
        }];
        [self getLocalPullDwon:[NSNumber numberWithInt:[orderId intValue]] andParentId:[NSNumber numberWithInt:[parentId intValue]]];
    } WithErrorBlock:^(id errorCode) {
        [self hiddenMbProgress];
    } WithFailureBlock:^{
        [self hiddenMbProgress];
    }];
    [myOrderViewModel getFinishOrderDwonPull:orderId andParentId:parentId];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
